package com.eliaukjq.xunlianying.duoxianchengjichu;

import java.util.WeakHashMap;

/**
 * @Author : 佩萁
 * Description :
 * @Create : 2024/7/21 - 8:53
 */
public class WeakHashMapExample {
    public static void main(String[] args) {
        WeakHashMap<MyKey, String> map = new WeakHashMap<>();

        MyKey key = new MyKey("Key1");
        map.put(key, "Value1");

        System.out.println("Before GC: " + map);

        // 取消对key的强引用
        key = null;

        // 强制垃圾回收
        System.gc();

        // 等待垃圾回收完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println("After GC: " + map);
    }
}

class MyKey {
    private String name;

    public MyKey(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}